﻿using Student.DAL;
using Student.Model;
using Student.Common;
using Student.ViewModel;
using Student.ViewModel.Enum;

namespace Student.BLL
{
    public class UserBO
    {
        public string Register(string userName, string password)
        {
            //判断是否已经注册过
            UserData? oldUser=new UserDAO().GetUser(userName);
            if (oldUser != null)
            {
                return "已经注册";
            }
            else
            {
                //准备新用户数据
                UserData user = new UserData
                {
                    UserName = userName,
                    Password = SecurityHelper.Sha512Encrypt(password)
                };

                //写入数据库用户数据表
                var result = new UserDAO().Insert(user);

                //返回结果
                if (result == 1)
                {
                    return "注册成功";
                }
                else
                {
                    return "注册失败";
                }
            }
        }

        public IResult Login(string userName, string password)
        {
            var msg = "";
            var user = new UserDAO().GetUser(userName);
            if (user == null) {
                msg = "没有该用户";
            }
            else
            {
                var pass = SecurityHelper.Sha512Encrypt(password);
                if (pass.Equals(user.Password))
                {
                    msg = "登录成功";
                    var token = new UserTokenBO().InsertUserToken(user.Id, 1);
                    return new DataResult<string>(token, ResultCode.Success, msg);
                }
                else
                {
                    msg = "密码错误";
                }
            }
            return new Result(ResultCode.Busy, msg);
        }
 
        public IResult GetList(dynamic data)
        {
            //当前data参数未使用
            var list = new UserDAO().GetList();
            return new DataResult<dynamic>(list);
        }
    }
}
